<template>
  <div class="applicationXQAdd">
    <el-dialog
      :title="pid?'编辑':'新增'"
      :visible.sync="centerDialogVisible"
      width="75%"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :before-close="close"
      class="dialog"

      >
      <div style="max-width:1000px;margin:auto;">
    <h4>申请信息</h4>
    <table border="1" rules="all" class="table">
      <tr>
        <td>标题</td>
        <td>
          <el-input v-model="addForm.title" placeholder="请输入标题"></el-input>
        </td>
        <td>申请人</td>
        <td class="title">{{applyUser}}</td>
      </tr>
      <tr>
        <td>采购类型</td>
        <td class="title">设备
         <!-- <el-select v-model="addForm.procureType" placeholder="请选择" clearable>
           <el-option v-for="item in proTypeList" :key="item.id" :label="item.deviceName"
                      :value="item.id"/>
          </el-select> -->
        </td>
        <td>采购计划</td>
        <td class="period">
          <!-- <el-select class="select" v-model="addForm.procureCircleType" placeholder="请选择" clearable>
            <el-option v-for="item in [{id:1,label:'年'},{id:2,label:'季'},{id:3,label:'月'}]" :key="item.id"
                       :label="item.label" :value="item.id"/>
          </el-select>
          <el-input v-model="addForm.procurePeriodYear" type="number" placeholder="年份"></el-input>
          <el-input v-model="addForm.procurePeriodQuarter" placeholder="季度/月份"></el-input> -->
          <el-select class="select" v-model="addForm.purchasePlanType" placeholder="请选择" clearable>
            <el-option v-for="item in [{id:1,label:'临时'},{id:2,label:'月度'},{id:3,label:'年度'}]" :key="item.id"
                       :label="item.label" :value="item.id"/>
          </el-select>
        </td>
      </tr>
      <tr>
        <td>备注</td>
        <td colspan="3">
          <el-input v-model="addForm.remark" type="textarea" :rows="2" placeholder="请输入备注"></el-input>
        </td>
      </tr>
    </table>
    <h4>设备清单</h4>
    <div class="btn left">
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="add">添加</el-button>

      <el-upload
        :action="baseUrl()+'/device/procurePlan/readExcel'"
        :headers="headers"
        accept=".xlsx, .xls"
        :on-success="excelSuccess"
        :show-file-list="false"
        style="display:inline-block;margin:0 10px;"
        >
        <el-button size="mini" type="info" icon="el-icon-upload">导入</el-button>
      </el-upload>
      <el-button size="mini" type="warning" icon="el-icon-upload" @click="importModel">导入模板</el-button>
    </div>
    <el-table :data="addForm.procureDevices" border>
      <el-table-column type="index" label="序号" width="55"/>
      <el-table-column label="设备名称" property="deviceName" width="200px">
        <template slot-scope="scope">
          <el-input v-model="scope.row.deviceName"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="规格型号" property="deviceModel" width="200px">
        <template slot-scope="scope">
          <el-input v-model="scope.row.deviceModel"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="数量" property="anticipatedProcureNum" width="100px">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.anticipatedProcureNum" :min="0"  :controls="false" @change="sum"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="设备/子设备" property="deviceUnit" width="150px">
        <template slot-scope="scope">
          <el-select v-model="scope.row.deviceLevel" placeholder="请选择" clearable>
            <el-option v-for="item in deviceLevelList" :key="item.id" :label="item.name"
                       :value="item.id"/>
          </el-select>
        </template>
      </el-table-column>
      <!-- <el-table-column label="预计单价" property="anticipatedProcurePrice">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.anticipatedProcurePrice" :min="0"  :controls="false"  @change="sum"></el-input-number>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="品牌" property="deviceBrand">
        <template slot-scope="scope">
          <el-input v-model="scope.row.deviceBrand"></el-input>
        </template>
      </el-table-column> -->
      <el-table-column label="单位" property="deviceUnit" width="150px">
        <template slot-scope="scope">
          <el-select v-model="scope.row.deviceUnit" placeholder="请选择" clearable>
            <el-option v-for="item in deviceUnitsList" :key="item.dictValue" :label="item.dictLabel"
                       :value="item.dictValue"/>
          </el-select>
        </template>
      </el-table-column>
      <!-- <el-table-column label="生产厂家" property="supplier">
        <template slot-scope="scope">
          <el-input v-model="scope.row.supplier"></el-input>
        </template>
      </el-table-column> -->
      <el-table-column label="需要程度" property="degreeNeed" width="200px">
        <template slot-scope="scope">
          <el-input v-model="scope.row.degreeNeed"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="用途" property="purpose" width="200px">
        <template slot-scope="scope">
          <el-input v-model="scope.row.purpose"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="使用单位" property="recipientsDeptId" width="150px">
        <template slot-scope="scope">
          <el-select v-model="scope.row.recipientsDeptId" placeholder="请选择" clearable>
            <el-option v-for="item in zrbmList" :key="item.deptId" :label="item.deptName"
                       :value="item.deptId"/>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="设备分类" property="deviceTypeName" width="150px">
        <template slot-scope="scope">
          <!-- <el-select v-model="scope.row.deviceTypeId" placeholder="请选择" clearable>
           <el-option v-for="item in proTypeList" :key="item.id" :label="item.deviceName"
                      :value="item.id"/>
          </el-select> -->
          <treeSelect @deviceType="((data)=>{deviceTypeChange(data,scope.row)})" :model="scope.row.deviceTypeName" type="deviceType"></treeSelect>

        </template>
      </el-table-column>
      <el-table-column label="备注" property="remark" width="200px">
        <template slot-scope="scope">
          <el-input v-model="scope.row.remark"></el-input>
        </template>
      </el-table-column>
      <!-- <el-table-column label="小计" prop="anticipatedSubtotal" /> -->
      <el-table-column label="操作" align="center"  width="100px">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="dele(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <div class="sum">
      <span class="h4">合计：数量</span><span class="int">{{addForm.anticipatedTotalNumber}}</span> <span class="h4">小计</span><span class="int">{{addForm.anticipatedTotalPrice}}</span>
    </div> -->

    <div class="upload">
      <el-upload
        :show-file-list="false"
        :action="baseUrl()+'/common/upload'"
        :on-success="fileSuccess">
        <el-button size="small" type="warning" icon="el-icon-folder-add">相关附件</el-button>
      </el-upload>
      <div class="unloadBox">
        <div class="file" v-for="(item,index) in addForm.annexes">
          <span class="index">{{index+1}}、</span>
          <span class="blue">{{item.fileName}}</span>
          <!--            <i class="blue el-icon-bottom" @click="fileDown(index,item.filePath)" ></i>-->
          <i class="blue el-icon-delete" @click="fileDel(index,item.filePath)"></i>
        </div>
      </div>
    </div>
    <div class="btn center ">
      <el-button type="primary" icon="el-icon-plus" size="mini" :loading="loading"  @click="submit(1)">保存</el-button>
      <el-button type="success" icon="el-icon-plus" size="mini" :loading="loading"  @click="submit(2)">提交</el-button>
    </div>
    <!--    <add-Product :routerData="transmitData" v-if="addshow" @callback="callback" ></add-Product>-->
</div>
    </el-dialog>
  </div>
</template>

<script>
  import { procurePlan, procurePlanDetail, procurePlanAdd, procurePlanEdit } from '@/api/purchase/index'
  import { getToken } from '@/utils/auth'
  import { treeselect } from '@/api/system/dept'
  import treeSelect from './treeSelect'
  import { deviceUnits, fileDelete, fileDownload, fileDeleteLibrary } from '@/api/basicInformation/index'
  import Cookies from 'js-cookie'
  import  {deviceType} from '@/api/device/index'
  import request from '@/utils/request'
  export default {
    name: 'applicationXQAdd',
    props:['pid'],
    components:{treeSelect},
    data() {
      return {
        loading:false,
        centerDialogVisible:true,
        headers: { Authorization: 'Bearer ' + getToken() },
        applyUser: Cookies.get('username'),
        addForm: {
          title: '',
          procureType: 1,
          // procureCircleType: '',
          // procurePeriodYear: '',
          // procurePeriodQuarter: '',
          purchasePlanType: '',
          remark: '',
          submitState:1,
          procureDevices: [],
          annexes: [],
          anticipatedTotalPrice:'',
          anticipatedTotalNumber:'',
        },
        deleteList: [],
        deviceUnitsList: [],
        procureDevices: [],
        zrbmList:[],
        proTypeList:[],
        defaultProps: {
          children: "list",
          label: "deviceName"
        },
        deviceLevelList:[{
          id: 1,
          name: "设备"
        },{
          id: 2,
          name: "子设备"
        }],
        dataList:[]
      }
    },

    created() {
      this.getDeviceUnits()
      this.getBumen()
      this.getDeviceType()
      if (this.pid) {
        this.getDetail(this.pid)
      }
    },
    methods: {
      close(){
        this.$emit('subSetChane')
      },
      async getDeviceType(){
        let res=await deviceType()
        this.dataList=res.rows
      },
      //获取部门信息
      getBumen(){
        request({
          url: '/system/dept/list',
          method: 'get',
        }).then(response => {
          this.zrbmList = response.data

        });
      },
      deviceTypeChange(data,row) {
        row.deviceTypeId=data.id
      },
      async getDetail(id) {
        let res = await procurePlanDetail(id)
        this.detailForm = res.data
        this.addForm = {
          id: res.data.id,
          title: res.data.title,
          procureType: res.data.procureType?res.data.procureType:1,
          // procureCircleType: res.data.procureCircleType,
          // procurePeriodYear: res.data.procurePeriodYear,
          // procurePeriodQuarter: res.data.procurePeriodQuarter,
          purchasePlanType: res.data.purchasePlanType,
          remark: res.data.remark,
          procureDevices: res.data.procureDevices,
          annexes: res.data.annexes,
          anticipatedTotalPrice:res.data.anticipatedTotalPrice,
          anticipatedTotalNumber:res.data.anticipatedTotalNumber,
        }
        this.procureDevices = res.data.procureDevices
      },
      /** 获取设备单位*/
      async getDeviceUnits() {
        let res = await deviceUnits()
        this.deviceUnitsList = res.data
      },
      //添加
      add() {
        let obj=
          {
            'anticipatedProcureNum': 0,
            'anticipatedProcurePrice': 0,
            'anticipatedSubtotal': '',
            'deviceBrand': '',
            'deviceCode': '',
            'deviceName': '',
            'deviceModel': '',
            'deviceUnit': '',
            'planId': '',
            'realProcureNum': '',
            'realProcurePrice': '',
            'realSubtotal': '',
            'remark': '',
            'status': '',
            'supplier': '',
            'deviceTypeName':''
          }

        // let a=this.addForm.procureDevices
        this.addForm.procureDevices.push(obj)
      },
      dele(index, row) {
        this.addForm.procureDevices.splice(index, 1)
        console.log(this.addForm.procureDevices)
        // this.$set(this.addForm.procureDevices,index,this.addForm.procureDevices[index])
        this.$message.success('删除成功')
      },
      fileSuccess(res) {
        this.addForm.annexes.push({ fileName: res.fileName, filePath: res.filePath, typeDistinguish: 1 })
      },
      async fileDel(index, filePath) {
        for (let i = 0; i < this.addForm.annexes.length; i++) {
          if (index == i) {
            if (this.addForm.annexes[i].id) {
              await fileDeleteLibrary(this.addForm.annexes[i].id)
            } else {
              await fileDelete(filePath)
            }
            this.addForm.annexes.splice(i, 1)
          }
        }
      },
      async submit(submitStateId) {

        //保存  or 提交
        if(submitStateId==2){
          this.addForm.verifyStatus=0
        }
        this.addForm.submitState = submitStateId;
        if (!this.addForm.title) {
          this.$message.error('请填写标题')
          return
        }
        if (!this.addForm.procureType) {
          this.$message.error('请选择采购类型')
          return
        }
        if (!this.addForm.purchasePlanType) {
          this.$message.error('请选择采购计划')
          return
        }
        // if (!this.addForm.procurePeriodYear) {
        //   this.$message.error('请填写采购周期')
        //   return
        // }
        // if (!this.addForm.procurePeriodQuarter) {
        //   this.$message.error('请填写采购周期')
        //   return
        // }
        // this.addForm.procureDevices = []
        // for (let i = 0; i < this.procureDevices.length; i++) {
        //   if (!this.procureDevices[i].deviceName || !this.procureDevices[i].deviceModel || !this.procureDevices[i].anticipatedProcureNum || !this.procureDevices[i].anticipatedProcurePrice) {
        //     return
        //   } else {
        //     this.addForm.procureDevices.push(this.procureDevices[i])
        //   }
        // }
        if (this.addForm.procureDevices.length == 0) {
          this.procureDevices = [],
            this.$message.error('请添加设备清单')
          return
        }
        this.loading = true
        let form = JSON.stringify(this.addForm)
        this.addForm.id ? await procurePlanEdit(form) : await procurePlanAdd(form)
        this.addForm.id ? this.$message.success('编辑成功') : this.$message.success('新增成功')
        // this.$router.push('/purchaseGL/cgju')
        this.$emit('subSetChane',1)
        this.loading = false
      },
      sum() {
        this.addForm.anticipatedTotalNumber= 0
        this.addForm.anticipatedTotalPrice=0
        for (let i = 0; i < this.procureDevices.length; i++) {
          this.procureDevices[i].anticipatedSubtotal=this.procureDevices[i].anticipatedProcureNum*this.procureDevices[i].anticipatedProcurePrice
          this.addForm.anticipatedTotalNumber= Number(this.procureDevices[i].anticipatedProcureNum) + Number(this.addForm.anticipatedTotalNumber)
          this.addForm.anticipatedTotalPrice = Number(this.procureDevices[i].anticipatedSubtotal) + Number(this.addForm.anticipatedTotalPrice)
        }
      },
      excelSuccess(res){
        //导入成功
        if(res.code==200){
          res.data.forEach(item => {
            let falg=false
            let falg1=false
            let falg2=false
            this.deviceUnitsList.forEach((i,index)=>{
              if(item.deviceUnit==i.dictLabel){
                item.deviceUnit=i.dictValue
                item.deviceUnitName=i.dictLabel
                falg=true
              }
              if(index==(this.deviceUnitsList.length-1)&&!falg){
                item.deviceUnit=null
                item.deviceUnitName=null
              }
            })
            this.zrbmList.forEach((i,index)=>{
              if(item.recipientsDeptName==i.deptName){
                item.recipientsDeptId=i.deptId
                falg1=true
              }
              if(index==(this.zrbmList.length-1)&&!falg1){
                item.recipientsDeptName=null
                item.recipientsDeptId=null
              }
            })
            falg2=this.setDeviceType(item.deviceTypeName,this.dataList)
            if(falg2){
              item.deviceTypeId=falg2
            }else{
              item.deviceTypeId=null
              item.deviceTypeName=null
            }

          });
          let a=this.addForm.procureDevices
          this.addForm.procureDevices=a.concat(res.data)
        }
      },
      setDeviceType(val,list){
        for (let i = 0; i < list.length; i++) {
          if(val==list[i].deviceName){
            console.log('123',list[i].id)
            return list[i].id
          }else{
            if(list[i].list&&list[i].list.length>0){
              return this.setDeviceType(val,list[i].list)

            }else{
              return false
            }
          }


        }

      },
      importModel(){
        window.location.href = this.baseUrl()+'/profile/templateDownload/采购计划表.xlsx'
      }

    }
  }
</script>
<style lang="scss">
  .applicationXQAdd {
    margin-left: 20px;
    .dialog .el-dialog__body{
      height: 85vh;
      overflow: scroll;
    }
    .blue {
      color: #2196F3;
    }

    h4 {
      color: #05A380;
    }

    .sum {
      margin-top: 20px;
      color: #666666;
      text-align: right;
      width: 1000px;

      .h4 {
        font-weight: bold;
      }

      .int {
        padding: 0 5px;
      }
    }

    .upload {
      margin-top: 20px;
      // width: 1000px;

      .unloadBox {
        border: 1px solid #cccccc;
        margin-top: 20px;
        min-height: 50px;
        overflow: hidden;

        .file {
          width: 100%;
          border-top: 1px #cccccc dotted;
          line-height: 50px;

          .index {
            padding: 0 10px;
            color: #666
          }

          i {
            float: right;
            line-height: 50px;
            padding-right: 10px;
            font-size: 20px;
            cursor: pointer;
          }

        }
      }
    }

    .table {
      border: 1px solid #cccccc;
      color: #606266;
      font-size: inherit;

      tr {
        .el-input--medium .el-input__inner, .el-textarea .el-textarea__inner {
          border: none;
        }

        td:nth-child(2n-1) {
          width: 180px;
          text-align: center;
        }

        td:nth-child(2n) {
          width: 320px;
        }

        .period {
          .select {
            width: 100px;
            float: left;
          }

          .el-input{
            width: 95px;
            float: left;
          }
        }

        .title {
          padding-left: 20px;
          text-align: left;
        }

        td {
          line-height: 35px;

          .el-select {
            width: 100%;
          }
        }
      }
    }

    .btn {
      margin-top: 20px;
      width: 1000px;
    }

    .left {
      text-align: left;
    }

    .center {
      text-align: center;
    }

    .el-table {
      margin-top: 20px;
      width: 1000px;
      .el-input-number--medium {
        width: 70px;
      }
    }
  }
</style>
